package com.iqiyi.pps.epg.web.timer;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.kiwi.utils.Configuration;
import com.iqiyi.pps.epg.core.model.statistic.StatisticProduceData;
import com.iqiyi.pps.epg.core.service.statistic.StatisticService;
import com.iqiyi.pps.epg.core.utils.ApiHttpRequestUtil;
import com.iqiyi.pps.epg.core.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

public class StatisticTrigger {
    public static final Logger logger = LoggerFactory.getLogger(StatisticTrigger.class);
    public static final String legoSearch = Configuration.getString("lego.search");

    @Autowired
    StatisticService statisticService;

    public void task() {
        logger.info("[StatisticTrigger] task");
        List<StatisticProduceData> statisticProduceDataList = statisticService.getCrontabProduceData();
        Map<Long, SameProgramId> map = new HashMap<Long, SameProgramId>();
        SameProgramId tmpSameProgramId = null;
        for (StatisticProduceData entity : statisticProduceDataList) {
            tmpSameProgramId = map.get(entity.getProgramId());
            if(tmpSameProgramId == null ){
                tmpSameProgramId = new SameProgramId();
                tmpSameProgramId.setProgramId(entity.getProgramId());
                map.put( tmpSameProgramId.getProgramId(),tmpSameProgramId);
            }
            tmpSameProgramId.addDataId(entity.getId());
        }
        List<Long> list = new ArrayList<Long>(map.keySet());
        int length = list.size();
        int onceNumber = 20;
        int repeatTime = length / onceNumber + (length % onceNumber == 0 ? 0 : 1);
        List<Long> temp = null;
        Map<String, String> params = new HashMap<String, String>();
        params.put("t", "0");
        String queryIds = null;
        for (int i = 0; i < repeatTime; i++) {
            temp = list.subList(i * onceNumber, (i * onceNumber + 20 > length ? length : i * onceNumber + 20));
            queryIds = temp.toString().replaceAll("\\[|\\]|\\s", "");
            params.put("filter_INL_entityId", queryIds);
            try {
                String rt = ApiHttpRequestUtil.doGet(legoSearch, null, params);
                if (null == rt) {
                    logger.info("[StatisticTrigger] [queryIds={}] empty", queryIds);
                    continue;
                }
                JSONObject rtJSON = JSON.parseObject(rt);
                if (Constants.CODE_SUC.equalsIgnoreCase(rtJSON.getString("code"))) {
                    JSONArray rtJSONArr = rtJSON.getJSONObject("data").getJSONArray("result");
                    if (rtJSONArr != null && rtJSONArr.size() != 0) {
                        doUpdate(map,rtJSONArr);
                    }
                }
            } catch (Exception e) {
                logger.error("[StatisticTrigger][task][queryIds=" + queryIds + "]", e);
            }
        }
        logger.info("[StatisticTrigger] end");
    }

    private void doUpdate(    Map<Long, SameProgramId> map , JSONArray rtJSONArr) {
        int length = rtJSONArr.size();
        JSONObject rtJSONObject = null;
        Map<String, String> parms = null;
        Long prId = 0L;
        SameProgramId tmpSameProgramId = null;
        for (int i = 0; i < length; i++) {
            rtJSONObject = rtJSONArr.getJSONObject(i);
            prId = rtJSONObject.getLongValue("entityId");
            long qipuId = rtJSONObject.getLongValue("qipuId");
            String releaseStatus = rtJSONObject.getString("releaseStatus");
            String pageFirstPublishTime = rtJSONObject.getString("pageFirstPublishTime");
            parms = new HashMap<String, String>();
            parms.put("qipuId", String.valueOf(qipuId));
            parms.put("pageFirstPublishTime", pageFirstPublishTime);
            parms.put("releaseStatus", releaseStatus);
            tmpSameProgramId =  map.get(prId);
            if(tmpSameProgramId != null){
                for( Long updateId : tmpSameProgramId.getList()){
                    statisticService.updateProduceData(updateId, parms);
                }
            }
        }
    }


}

class SameProgramId {
    private long programId;
    private List<Long> list = new ArrayList<Long>();

    public long getProgramId() {
        return programId;
    }

    public void setProgramId(long programId) {
        this.programId = programId;
    }

    public List<Long> getList() {
        return list;
    }

    public void addDataId(Long dataId){
        list.add(dataId);
    }
}
